package com.antilia.infomaresme.form;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import org.apache.wicket.Component;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.RadioGroup;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.util.visit.IVisit;
import org.apache.wicket.util.visit.IVisitor;
import org.wiquery.plugin.jquertytools.tooltip.TooltipBehavior.Offset;
import org.wiquery.plugin.jquertytools.tooltip.TooltipBehavior.Position;

/**
 * 
 * @author Ernesto Reinaldo Barreiro
 */
public class ShinyFormVisitor implements IVisitor<Component, Void>, Serializable {

	private static final long serialVersionUID = 1L;

	Set<Component> visited = new HashSet<Component>();
	
	private boolean wantHelpTooltips;
	
	private boolean errorHighlightBehavior;
	
	private boolean validationMessage;
	
	/**
	 * Constructor.
	 */
	public ShinyFormVisitor(boolean wantHelpTooltips, boolean errorHighlightBehavior, boolean validationMessage) {
		this.wantHelpTooltips = wantHelpTooltips;
		this.errorHighlightBehavior = errorHighlightBehavior;
		this.validationMessage = validationMessage;
	}
	
	
	public void clearVisited() {
		visited.clear();
	}


	public void component(Component c, IVisit<Void> visit) {
		if (!visited.contains(c))
		{
			if(c instanceof FormComponent<?>) {
				visited.add(c);
				if(errorHighlightBehavior)
					c.add(new ErrorHighlightBehavior());
				c.add(new ValidationMessageBehavior(wantHelpTooltips, validationMessage));				
				FormComponent<?> fc = (FormComponent<?>)c;
				if(fc instanceof TextField<?> || fc instanceof DropDownChoice<?> || fc instanceof RadioGroup<?>) {		
					if(wantHelpTooltips) {
						c.add(new TemporaryTooltipBehavior()
						.setOffset(new Offset(20, 0))
						.setPosition(Position.top_left)
						.setRelative(true));		
					} else if(validationMessage && !fc.isValid()){
						c.add(new TemporaryTooltipBehavior()
						.setOffset(new Offset(20, 0))
						.setPosition(Position.top_left)
						.setRelative(true));
					}
				}				
			}
		}
	}

}
